import React from 'react'
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from '@fullcalendar/timegrid'
import interactionPlugin from '@fullcalendar/interaction' // needed for dayClick
import '@fullcalendar/core/main.css';
import '@fullcalendar/daygrid/main.css';
import '@fullcalendar/timegrid/main.css';

import moment from 'moment';

import LayoutContentWrapper from '@iso/components/utility/layoutWrapper';
import LayoutContent from '@iso/components/utility/layoutContent';
import Button from '@iso/components/uielements/button';
import Modals from '@iso/components/Feedback/Modal';
import Input, { Textarea } from '@iso/components/uielements/input';
import {Fieldset, Form, Label} from "../../../FirestoreCRUD/Article/Article.styles";

import ModalStyle from "../../../Feedback/Modal/Modal.styles";
import WithDirection from '@iso/lib/helpers/rtl';
import axios from "../../../../http";
import Qs from 'qs'
import message from '@iso/components/Feedback/Message';
import MessageContent from "../../../Feedback/Message/Message.styles";
import Popconfirms from '@iso/components/Feedback/Popconfirm';
import PopconfirmWrapper from "../../../Feedback/Popconfirm/Popconfirm.styles";
import PageHeader from '@iso/components/utility/pageHeader';
import Alert from '@iso/components/Feedback/Alert';

const Popconfirm = (props) => (
    <PopconfirmWrapper>
        <Popconfirms {...props} />
    </PopconfirmWrapper>
);
const isoModal = ModalStyle(Modals);
const Modal = WithDirection(isoModal);

export default class MyReport extends React.Component {


    constructor(props) {

        super(props);

        this.state={eventList:[],userList:[],userViewList:[],modalVisible:false,modalEditVisible:false,modalViewVisible:false,calendarWeekends:true};

    }
    calendarComponentRef = React.createRef()

    showAddModal=(selectionInfo)=>{

        let start=this.format(selectionInfo.start)+" 9:00:00"

        let end=this.format(selectionInfo.start)+" 18:00:00"

        let reportDate=this.format(selectionInfo.start);

        let weekDate=this.getWeekOfDate(this.format(selectionInfo.start));

        let existDayReport=this.checkExistReport(reportDate,"DAY")

        if(weekDate!='周五'){
            if(existDayReport==true){
                return ;
            }
            this.setState({type:'DAY',workContentTitle:'当日',nextWorkPlanTitle:'次日',modalVisible:true,start:start,end:end,workContent:'',nextWorkPlan:'',memo:''})
            return ;
        }

        if(weekDate=='周五'){
            let existWeekReport=this.checkExistReport(reportDate,"WEEK")
            if(existDayReport==true&&existWeekReport==true){
                return ;
            }
            if(existDayReport==false){
                this.setState({type:'DAY',workContentTitle:'当日',nextWorkPlanTitle:'次日',modalVisible:true,start:start,end:end,workContent:'',nextWorkPlan:'',memo:''})
                return ;
            }
            if(existWeekReport==false){
                this.setState({type:'WEEK',workContentTitle:'本周',nextWorkPlanTitle:'下周',modalVisible:true,start:start,end:end,workContent:'',nextWorkPlan:'',memo:''})
                return ;
            }
        }

    };

    format=(date)=>{
        return moment(date).format('YYYY-MM-DD');
    }
    getWeekOfDate=(dateString)=> {
        let dateArray = dateString.split("-");
        let date = new Date(dateArray[0], parseInt(dateArray[1] - 1), dateArray[2]);
        return "周" + "日一二三四五六".charAt(date.getDay());
    };
    checkExistReport = (reportDate, type) => {
        let eventApiList = this.calendarComponentRef.current.getApi().getEvents()
        for(let i=0;i<eventApiList.length;i++){
            let eventApi=eventApiList[i];
            console.log('start',eventApi.start)
            if(this.format(eventApi.start)===reportDate&&eventApi.extendedProps.type===type){
                return true;
            }
        }
        return false;
    }

    handleCancel = () => {
        this.setState({modalVisible:false})
    };

    eventClick=(selectionInfo)=>{

        let start=this.format(selectionInfo.start)+" 9:00:00"

        let end=this.format(selectionInfo.end)+" 18:00:00"

        let state={modalEditVisible:true,id:selectionInfo.event.id,start:start,end:end,memo:selectionInfo.event.extendedProps.memo,workContent:selectionInfo.event.extendedProps.workContent,nextWorkPlan:selectionInfo.event.extendedProps.nextWorkPlan};

        this.setState(state)

        if(selectionInfo.event.extendedProps.type=='WEEK'){
            this.setState({workContentTitle:'本周',nextWorkPlanTitle:'下周'})
        }
        if(selectionInfo.event.extendedProps.type=='DAY'){
            this.setState({workContentTitle:'当日',nextWorkPlanTitle:'次日'})
        }
    };

    handleEditCancel = () => {
        this.setState({modalEditVisible:false})
    };

    handleViewCancel = () => {
        this.setState({modalViewVisible:false})
    };
    onRecordChange = (event, key) => {
        let state={};
        state[key]=event.target.value;
        this.setState(state)
    };

    componentDidMount() {

    }

    add=() =>{
        let entity={workContent:this.state.workContent,nextWorkPlan:this.state.nextWorkPlan,start:this.state.start,end:this.state.end,memo:this.state.memo,type:this.state.type};
        axios.post('api/oa/work/report/add', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalVisible:false})
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }
            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }

    update=() =>{
        let entity={id:this.state.id,workContent:this.state.workContent,nextWorkPlan:this.state.nextWorkPlan,memo:this.state.memo};
        axios.post('api/oa/work/report/update', Qs.stringify({
            requestJson:JSON.stringify(entity)
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalEditVisible:false})
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }



    deleteById=()=> {
        axios.post('api/oa/work/report/deleteById', Qs.stringify({
            id:this.state.id
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data;
                if(data.status==1){
                    this.setState({modalEditVisible:false})
                    this.showSuccessMessage(data.message)
                }else{
                    this.showErrorMessage(data.message);
                }

            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });

    }


    loadEvents=(eventInfo,successCallback, failureCallback)=>{
        axios.post('api/oa/work/report/findMyAll', Qs.stringify({
            start:moment(eventInfo.start).format('YYYY-MM-DD HH:mm:ss'),
            end:moment(eventInfo.end).format('YYYY-MM-DD HH:mm:ss')
        }),{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .then((response)=>{
                let  data=response.data.data;
                for(let i=0;i<data.length;i++){
                    if(data[i]["type"]=='WEEK'){
                        data[i]["backgroundColor"]='green'
                    }
                }
                successCallback (data)
            })
            .catch(function (error) {
                this.showErrorMessage(error);
            });
    }

    showSuccessMessage (systemMessage){
        message.success(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };
    showErrorMessage (systemMessage){
        message.error(
            <MessageContent>
                {systemMessage}
            </MessageContent>,
            5
        );
    };
    marginBot = {
        marginBottom: '10px',
    };

    render() {
        return (
            <LayoutContentWrapper >
                <PageHeader>
                    我的报告
                </PageHeader>
                <LayoutContent>

                    <Modal
                        visible={this.state.modalVisible}
                        title="添加"
                        onCancel={this.handleCancel}
                        footer={[
                            <Button key="back" size="small" onClick={this.handleCancel}>
                                取消
                            </Button>,
                            <Button
                                key="submit"
                                type="primary"
                                size="small"
                                onClick={this.add}
                            >
                                确定
                            </Button>,
                        ]}
                    >
                        <Form>
                            <Fieldset>
                                <Label>*开始时间:{this.state.start}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*结束时间:{this.state.end}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>{this.state.workContentTitle}工作内容</Label>
                                <Textarea
                                    label="工作内容"
                                    placeholder="工作内容"
                                    rows={5}
                                    value={this.state.workContent}
                                    onChange={e => this.onRecordChange(e, 'workContent')}
                                />
                            </Fieldset>
                            <Fieldset>
                            <Label>{this.state.nextWorkPlanTitle}工作计划</Label>
                            <Textarea
                                label="工作计划"
                                placeholder="工作计划"
                                rows={5}
                                value={this.state.nextWorkPlan}
                                onChange={e => this.onRecordChange(e, 'nextWorkPlan')}
                            />
                           </Fieldset>

                            <Fieldset>
                                <Label>备注</Label>
                                <Textarea
                                    label="备注"
                                    placeholder="备注"
                                    rows={5}
                                    value={this.state.memo}
                                    onChange={e => this.onRecordChange(e, 'memo')}
                                />
                            </Fieldset>
                        </Form>
                    </Modal>

                    <Modal
                        visible={this.state.modalEditVisible}
                        title="编辑"
                        onCancel={this.handleEditCancel}
                        footer={[
                            <Button key="back" size="small" onClick={this.handleEditCancel}>
                                取消
                            </Button>,
                            <Button
                                key="submit"
                                type="primary"
                                size="small"
                                onClick={this.update}
                            >
                                确定
                            </Button>,
                        ]}
                    >
                        <Form>
                            <Fieldset>
                                <Label>*开始时间:{this.state.start}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>*结束时间:{this.state.end}</Label>
                            </Fieldset>
                            <Fieldset>
                                <Label>{this.state.workContentTitle}工作内容</Label>
                                <Textarea
                                    label="工作内容"
                                    placeholder="工作内容"
                                    rows={5}
                                    value={this.state.workContent}
                                    onChange={e => this.onRecordChange(e, 'workContent')}
                                />
                            </Fieldset>
                            <Fieldset>
                                <Label>{this.state.nextWorkPlanTitle}工作计划</Label>
                                <Textarea
                                    label="工作计划"
                                    placeholder="工作计划"
                                    rows={5}
                                    value={this.state.nextWorkPlan}
                                    onChange={e => this.onRecordChange(e, 'nextWorkPlan')}
                                />
                            </Fieldset>

                            <Fieldset>
                                <Label>备注</Label>
                                <Textarea
                                    label="备注"
                                    placeholder="备注"
                                    rows={5}
                                    value={this.state.memo}
                                    onChange={e => this.onRecordChange(e, 'memo')}
                                />
                            </Fieldset>
                            <Fieldset>
                                <Popconfirm
                                    title="确定要执行删除操作吗？"
                                    okText="是"
                                    cancelText="否"
                                    onConfirm={this.deleteById}
                                >
                                    <Button
                                        key="submit"
                                        type="danger"
                                        size="small"

                                    >
                                        删除
                                    </Button>
                                </Popconfirm>

                            </Fieldset>
                        </Form>
                    </Modal>

                    <Alert
                        message={'请在周五填写周报，周五填写完日报后即可填写周报。'}
                        type="warning"
                        style={this.marginBot}
                    />

                    <FullCalendar
                        defaultView="dayGridMonth"
                        header={{
                            left: 'prev,next today',
                            center: 'title',
                            right: 'dayGridMonth'
                        }}

                        plugins={[ dayGridPlugin, timeGridPlugin, interactionPlugin ]}
                        ref={ this.calendarComponentRef }
                        weekends={ this.state.calendarWeekends }

                        events={(eventInfo,successCallback, failureCallback)=>{this.loadEvents(eventInfo,successCallback,failureCallback)}}

                        editable={true}
                        selectable={true}
                        selectMirror={true}
                        select={(selectionInfo)=>{this.showAddModal(selectionInfo)}}
                        displayEventTime={false}
                        locale='zh-cn'
                        firstDay={1}
                        buttonText={{
                            today: '今天',
                            month: '月',
                            week: '周',
                            day: '天'
                        }}

                        allDayText='全天'
                        slotLabelFormat={{
                            hour: '2-digit',
                            minute: '2-digit',
                            meridiem: false,
                            hour12: false
                        }}
                        eventRender={(info)=>{}}
                        eventClick={this.eventClick}

                    />


                </LayoutContent>
            </LayoutContentWrapper>

        )
    }







}
